package com.homedo.microservice.distributed.id.service.remote.api.impl;

import com.homedo.common.util.Detect;
import com.homedo.microservice.distributed.id.service.api.IGenerateIdServiceRemote;
import com.homedo.microservice.distributed.id.service.exception.LeafServerException;
import com.homedo.microservice.distributed.id.service.exception.NoKeyException;
import com.homedo.microservice.distributed.id.service.service.LeafAllocService;
import com.homedo.microservice.distributed.id.service.service.SegmentService;
import com.sankuai.inf.leaf.common.Result;
import com.sankuai.inf.leaf.common.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GenerateIdServiceRemoteImpl implements IGenerateIdServiceRemote {

    private static final Logger _LOGGER = LoggerFactory.getLogger(GenerateIdServiceRemoteImpl.class);

    @Autowired
    private SegmentService segmentService;
    @Autowired
    private LeafAllocService leafAllocService;

    @Override
    public String generateId(@PathVariable("key") String key) {
        if (!Detect.notEmpty(key)) {
            throw new NoKeyException();
        }

        if (!leafAllocService.checkExist(key)) {
            try {
                leafAllocService.save(key, null);
            } catch (Exception ex) {
                //可忽略此异常
                _LOGGER.error("[保存key出错:{}]", ex.getMessage());
            } finally {
                segmentService.getIdGen().updateCacheFromDb();
            }
        }

        return get(segmentService.getId(key));
    }

    private String get(Result id) {
        Result result = id;

        if (result.getStatus().equals(Status.EXCEPTION)) {
            throw new LeafServerException(result.toString());
        }
        return String.valueOf(result.getId());
    }

}
